package lambda;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * lambda和集合容器
 * <pre>
 * 容器中新增方法
 * Collection removeIf() spliterator() stream() parallelStream() forEach()
 * List	      replaceAll() sort()
 * Map        getOrDefault() forEach() replaceAll() putIfAbsent() remove() replace() computeIfAbsent() computeIfPresent() compute() merge()
 * <pre/>
 * @author <a href="mailto:sjj@jianzhimao.com">mojo</a>
 * copyright (C), 2013-2022, 广州九尾信息科技有限公司
 * @date 2022/3/23 14:24
 */
public class LambdaAndCollection {
    public static void main(String[] args) {
        //collectionTest();
        listTest();
        //mapTest();
    }

    //map新增方法
    private static void mapTest() {
        HashMap<Object, Object> map = new HashMap<>();
        map.put("1", null);
        map.put("2", "two");
        map.put("3", "three");
        //foreach
        map.forEach((k, v) -> {
            System.out.print(k);
            System.out.println(v);
        });
        //putIfAbsent,不存在key值的映射或映射值为null时
        Object four = map.putIfAbsent("3", "four");
        System.out.println(four);
        //replaceAll
        map.replaceAll((k, v) -> v + ">>");
        map.forEach((k, v) -> {
            System.out.print(k);
            System.out.println(v);
        });
        //merge,map.merge(key, newMsg, (v1, v2) -> v1+v2);
        map.merge(1, "null", (v1, v2) -> "" + v1 + v2);
        System.out.println(map.values());
    }

    //list新增方法
    private static void listTest() {

        //replaceAll
        List<String> strings = new ArrayList<>(Arrays.asList("today", "is", "wednesday"));
        strings.replaceAll(s -> {
            if (s.length() > 3) {
                return s.toUpperCase();
            }
            return s;
        });
        strings.forEach(System.out::println);
        //sort
        strings.sort(String::compareTo);
        System.out.println(">>>>>>>>>>>>sort");
        for (String s : strings.stream()
                .filter(s -> s.length() > 4)
                .sorted(Comparator.comparingInt(String::length)).collect(Collectors.toList())) {
            System.out.println(s);
        }

    }

    //collection新增方法
    private static void collectionTest() {
        //stream
        List<Integer> list = new ArrayList<>(Arrays.asList(1, 2, 3)).stream().filter(t -> (t > 1))
                .collect(Collectors.toList());
        //foreach方法
        list.forEach(e -> {
            if (e > 1) {
                System.out.println(e);
            }
        });
        //removeIf
        List<Integer> list1 = new ArrayList<>(Arrays.asList(1, 2, 3));
        list1.removeIf(e -> e > 2);
        list1.forEach(System.out::println);

    }
}
